package com.atguigu.gmall.product.service;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.mq.config.MqConst;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.service.RabbitService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.bytebuddy.asm.Advice;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 李旭
 * @Time: 15:36
 * @Description:
 *
 *
 */
@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    // //查询一级分类集合
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }


    // //查询二级分类集合
    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
          .eq("category1_id",category1Id));
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id",category2Id));
    }

    //#根据一二三级分类的ID  层级查询 平台属性及属性值表
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id,category2Id,category3Id);
    }
    //添加平台属性及值
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //1:平台属性表  1    1
        baseAttrInfoMapper.insert(baseAttrInfo);
        //2:平台属性值表 N   2
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        attrValueList.forEach(baseAttrValue -> {
            //外键
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        });
    }
    //查询品牌列表 （分页
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page(page, limit), null);
    }
    //查询SPU商品列表  （分页）
    @Override
    public IPage spuInfoList(Integer page, Integer limit, Long category3Id) {
        return spuInfoMapper.selectPage(new Page(page,limit),new QueryWrapper<SpuInfo>()
          .eq("category3_id",category3Id));
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }


    //商品添加
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1:商品表
        spuInfoMapper.insert(spuInfo);
           //2;图片表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if(!CollectionUtils.isEmpty(spuImageList)){
            spuImageList.forEach(spuImage -> {
                //外键
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });

        }
        //3:销售属性表
        spuInfo.getSpuSaleAttrList().forEach(spuSaleAttr -> {
            //外键
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4:销售属性值表
            spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                //外键
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                //销售属性名称
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });



    }
    //根据商品ID spuId 查询所有图片 显示在Sku添加页面 目标：为了让管理员来选择
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().
                eq("spu_id",spuId));
    }
    //根据SpuId查询销售属性及属性值
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }


    //添加SkuInfo
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {

        //1:库存表
        skuInfoMapper.insert(skuInfo);
        //2:库存的图片表
        skuInfo.getSkuImageList().forEach(skuImage -> {
            //外键
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //3:库存与平台属性及值的中间表
        skuInfo.getSkuAttrValueList().forEach(skuAttrValue -> {
            //外键
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //4:库存与销售属性及值的中间表
        skuInfo.getSkuSaleAttrValueList().forEach(skuSaleAttrValue -> {

            //商品ID 外键
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            //库存ID 外键
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }

    //SKU分页查询
    @Override
    public IPage skuListPage(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page(page,limit),null);
    }

    @Autowired
    private RabbitService rabbitService;
    //上架
    @Override
    public void onSale(Long skuId) {
        //1:修改DB中库存表 is_sale
        //  不走1.1 先查询  select * from sku_info where id = ?  连接mysql
        //  直接走1.2 再修改 update sku_info set is_sale = 1 where id = ? 连接mysql
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);//问题： 硬编码问题   2表示上架
        skuInfoMapper.updateById(skuInfo);
        //2：发消息 更新ES索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.CANCELSALE);//问题： 硬编码问题   2表示上架
        skuInfoMapper.updateById(skuInfo);
        //2：发消息 删除索引库
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,skuId);
    }


    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;//解决分布式相关问题  分布式锁的相关问题
    //直接使用RedissonClient来解决分布式锁问题
    @Override
    //@GmallCache(prefix = "sku:")  //表示要加缓存  解决三大问题   标记  Aop切面
    //@Transactional(rollbackFor = IOException.class) //RuntimeException 及的子异常的时候回   IOExcetion
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存Key值
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        //1:先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if(null == skuInfo){
            //上锁 解决缓存击穿
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            //过期不候的锁 JUC
            //参数1：获取锁的时间 过了这个时间就不再获取了
            //参数2：获取到锁之后 锁的过期时间
            //参数3：单位
            try {
                boolean tryLock = lock.tryLock(1, 4, TimeUnit.SECONDS);
                if(tryLock){
                    //获取到了锁
                    //2:没有 查询DB
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if(null != skuInfo){
                        skuInfo.setSkuImageList(skuImageMapper.
                                selectList(new QueryWrapper<SkuImage>().eq("sku_id",skuId)));
                        //再保存缓存一份
                        redisTemplate.opsForValue().set(cacheKey,skuInfo,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300),//缓存雪崩
                                TimeUnit.SECONDS);
                    }else{
                        // 缓存穿透   空结果  应付攻击者  DB
                        skuInfo = new SkuInfo();
                        //再保存缓存一份
                        redisTemplate.opsForValue().set(cacheKey,
                                skuInfo,5,
                                TimeUnit.MINUTES);
                    }
                    //解锁
                    lock.unlock();
                }else{
                    //未获取锁
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //有
        return skuInfo;
    }
    //根据SKUID获取SKUINFO信息  图片
    //直接使用redis 来解决分布式锁问题
   /* @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存Key值
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId +
                RedisConst.SKUKEY_SUFFIX;
        //1:先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if(null == skuInfo){
            //分布式锁的Key值
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            //解决缓存击穿问题   上分布式锁
            //UUID 36长度 去掉四个小横线  32位长度
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey, uuid
                ,1,TimeUnit.SECONDS);
            if(lock){
                //获取到了锁
                //2:没有 查询DB
                skuInfo = skuInfoMapper.selectById(skuId);
                if(null != skuInfo){
                    skuInfo.setSkuImageList(skuImageMapper.
                            selectList(new QueryWrapper<SkuImage>().eq("sku_id",skuId)));
                    //再保存缓存一份
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,
                            RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300),//缓存雪崩
                            TimeUnit.SECONDS);
                }else{
                    // 缓存穿透   空结果  应付攻击者  DB
                    skuInfo = new SkuInfo();
                    //再保存缓存一份
                    redisTemplate.opsForValue().set(cacheKey,
                            skuInfo,5,
                            TimeUnit.MINUTES);
                }
                //删除了
                //判断是否是自己的锁
         *//*       Object u = redisTemplate.opsForValue().get(cacheLockKey);
                if(uuid.equals(u)){
                    //是自己的锁
                    redisTemplate.delete(cacheLockKey);
                }*//*
                //LUA脚本   Nginx或redis  C语言开发软件  LUA脚本 C语言开发的
                //删除具备原子性操作
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);
            }else{
                //未获取到锁
                try {
                    TimeUnit.SECONDS.sleep(2);
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //3:统一返回
        return skuInfo;
    }*/

    //三级分类的视图
    @Override
    @GmallCache(prefix = "baseCategoryView:")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }
    //销售属性及值及选中红边框
    @Override
    @GmallCache(prefix = "getSpuSaleAttrValueChecked:")
    public List<SpuSaleAttr> getSpuSaleAttrValueChecked(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrValueChecked(skuId,spuId);
    }
    //销售属性值组合对应库存ID    入参：商品ID spuId   手写SQL
    @Override
    @GmallCache(prefix = "getValuesSkuJson:")
    public Map getValuesSkuJson(Long spuId) {
        Map result = new HashMap();
        List<Map> listMap = skuSaleAttrValueMapper.getValuesSkuJson(spuId);
        listMap.forEach(map -> {
            result.put(map.get("valueIds"),map.get("sku_id"));
        });
        return result;
    }

    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if(null != skuInfo){
            return skuInfo.getPrice();
        }else{
            return null;
        }
    }

    // //查询三级分类视图集合
    @Override
    public List<BaseCategoryView> getBaseCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }
    //根据主键查询品牌对象
    @Override
    public BaseTrademark getBaseTrademark(Long id) {
        return baseTrademarkMapper.selectById(id);
    }
    //查询ES索引库所需要的平台属性ID及名称及值
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }

    @Autowired
    private  BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
}
